const fs = require('fs');
const path = require('path');

/**
 * 生成项目目录结构
 * @module utils/directoryTree
 * @version 1.0.0
 */

/**
 * 递归生成目录结构
 * @param {string} dirPath 目录路径
 * @param {number} level 当前层级
 * @param {number} maxLevel 最大层级
 * @returns {string} 目录结构字符串
 */
function generateTree(dirPath, level = 0, maxLevel = 5) {
    if (level > maxLevel) return '';
    
    const items = fs.readdirSync(dirPath, { withFileTypes: true });
    
    // 将目录和文件分开
    const directories = items.filter(item => item.isDirectory());
    const files = items.filter(item => item.isFile());
    
    // 合并，先目录后文件
    const sortedItems = [...directories, ...files];
    
    let result = '';

    // 如果是根目录，显示"项目根目录"
    if (level === 0) {
        result += '项目根目录\n';
    }

    sortedItems.forEach((item, index) => {
        // 忽略 node_modules 和 .git 目录
        if (item.name === 'node_modules' || item.name === '.git') return;

        // 添加缩进
        const prefix = '│   '.repeat(level);
        const isLast = index === sortedItems.length - 1;
        const connector = isLast ? '└── ' : '├── ';
        result += `${prefix}${connector}${item.name}\n`;

        // 如果是目录，递归处理
        if (item.isDirectory()) {
            const childResult = generateTree(path.join(dirPath, item.name), level + 1, maxLevel);
            if (childResult) {
                result += childResult;
            }
        }
    });

    return result;
}

/**
 * 生成目录结构并写入 README.md
 * @async
 * @function generateDirectoryTree
 * @returns {Promise<void>}
 */
async function generateDirectoryTree() {
    return new Promise((resolve, reject) => {
        try {
            const tree = generateTree(process.cwd());
            const newContent = `# 项目目录结构\n\`\`\`\n${tree}\n\`\`\``;
            
            // 读取现有 README.md 内容
            let existingContent = '';
            if (fs.existsSync('README.md')) {
                existingContent = fs.readFileSync('README.md', 'utf8');
            }

            // 替换或添加目录结构部分
            const updatedContent = existingContent.includes('# 项目目录结构')
                ? existingContent.replace(
                    /# 项目目录结构[\s\S]*?(?=#|$)/,
                    newContent
                  )
                : `${newContent}\n\n${existingContent}`;
            
            fs.writeFile('README.md', updatedContent, (err) => {
                if (err) {
                    console.warn('⚠️ 写入 README.md 失败:', err.message);
                    return reject(err);
                }
                console.log('✅ 目录结构已成功更新到 README.md');
                resolve();
            });
        } catch (error) {
            console.warn('⚠️ 生成目录结构失败:', error.message);
            reject(error);
        }
    });
}

module.exports = generateDirectoryTree; 